import React, {Component} from 'react';
import localStorage from "../../helper/ls";
import {userLogin, userRegister} from "../../api/user";

class User extends Component {

  constructor(props) {
    super(props);

    this.state = {
      username: '',
      password: '',
      error: '',
      success: '',
    };
  }

  handleUsernameChange = e => {
    this.setState({
      username: e.target.value
    });
  };

  handlePasswordChange = e => {
    this.setState({
      password: e.target.value
    });
  };

  handleRegisterClick = async () => {
    const {username, password} = this.state;
    const params = {username, password};
    try {
      const data = await userRegister(params);
      this.setState({success: `${username} 注册成功`, error: null})
      localStorage.set('user', data);
    } catch (err) {
      this.setState({error: err.msg})
    }
  };

  handleLoginClick = async () => {
    const {username, password} = this.state;
    const params = {username, password};
    try {
      const data = await userLogin(params);
      this.setState({success: `${username} 登录成功`, error: null})
      localStorage.set('user', data);
      this.props.handleUserLogin(data);
    } catch (err) {
      console.log(err);
      this.setState({error: err.msg})
    }
  };

  render() {
    return (
      <div className="main">
        <div className="login">
          <p>username: <input type="text" value={this.state.username} onChange={this.handleUsernameChange}/></p>
          <p>password: <input type="text" value={this.state.password} onChange={this.handlePasswordChange}/></p>
          <p className="btns">
            <button onClick={this.handleRegisterClick}>注册</button>
            <button onClick={this.handleLoginClick}>登录</button>
          </p>
          {this.state.error && <p className="error">{this.state.error}</p>}
          {this.state.success && <p className="success">{this.state.success}</p>}
        </div>
      </div>
    );
  }
}

export default User;
